<template>
	<view class="container">
		<!-- 搜索头部 -->
		<!-- 顶部Header -->
		<view class="header">
			<view class="header-left">
				<u-icon name="arrow-left" size="40" color="#ffffff" @click="goBack"></u-icon>
			</view>
			<view class="header-title">AI智慧点歌</view>
			<view class="header-right">
				<view class="header-right-button">
					<u-icon name="more-dot-fill" size="32" color="linear-gradient(180deg, #0d0d11 0%, #1a1a1f 100%)" @click="onDevelopingFeature"></u-icon>
					<u-icon name="scan" size="32" color="linear-gradient(180deg, #0d0d11 0%, #1a1a1f 100%)" style="margin-left: 20rpx" @click="onDevelopingFeature"></u-icon>
				</view>
			</view>
		</view>
		<view class="search-header">
			<view class="search-bar">
				<u-icon name="search" color="#999999" size="32"></u-icon>
				<input class="search-input" placeholder="搜索歌星、歌名" v-model="searchKeyword" @input="onSearchInput" @confirm="onSearchConfirm" :focus="true" />
				<view class="search-cancel" @click="goBack">
					<text>取消</text>
				</view>
			</view>
		</view>

		<!-- 搜索建议 -->
		<view v-if="searchSuggestions.length > 0 && !hasSearched" class="suggestions-container">
			<view class="suggestions-title">搜索建议</view>
			<view class="suggestions-list">
				<view v-for="(suggestion, idx) in searchSuggestions" :key="idx" class="suggestion-item" @click="selectSuggestion(suggestion)">
					<u-icon name="search" size="24" color="#888888"></u-icon>
					<text class="suggestion-text">{{ suggestion }}</text>
				</view>
			</view>
		</view>

		<!-- 热门搜索 -->
		<view v-if="!hasSearched" class="hot-search-container">
			<view class="hot-search-title">热门搜索</view>
			<view class="hot-search-tags">
				<view v-for="(tag, idx) in hotSearchTags" :key="idx" class="hot-tag" @click="selectHotTag(tag)">
					{{ tag }}
				</view>
			</view>
		</view>

		<!-- 搜索历史 -->
		<view v-if="searchHistory.length > 0 && !hasSearched" class="history-container">
			<view class="history-header">
				<text class="history-title">搜索历史</text>
				<u-icon name="trash" size="24" color="#888888" @click="clearHistory"></u-icon>
			</view>
			<view class="history-list">
				<view v-for="(history, idx) in searchHistory" :key="idx" class="history-item" @click="selectHistory(history)">
					<u-icon name="clock" size="24" color="#888888"></u-icon>
					<text class="history-text">{{ history }}</text>
					<u-icon name="close" size="20" color="#666666" @click.stop="removeHistory(idx)"></u-icon>
				</view>
			</view>
		</view>

		<!-- 搜索结果 -->
		<view v-if="hasSearched" class="search-results">
			<!-- 结果统计 -->
			<view class="result-stats">
				<text>找到 {{ totalResults }} 个结果</text>
			</view>

			<!-- 结果分类 -->
			<view class="result-tabs">
				<view v-for="(tab, idx) in resultTabs" :key="idx" :class="['result-tab', { active: activeTabIndex === idx }]" @click="switchTab(idx)">
					{{ tab.name }}
					<text class="tab-count" v-if="tab.count > 0">({{ tab.count }})</text>
				</view>
			</view>

			<!-- 加载状态 -->
			<view v-if="isSearching" class="loading-container">
				<view class="loading-spinner"></view>
				<text class="loading-text">正在搜索...</text>
			</view>

			<!-- 歌曲结果 -->
			<view v-else-if="activeTabIndex === 0" class="songs-results">
				<view v-if="searchResults.songs.length > 0" class="songs-list">
					<view v-for="(song, idx) in searchResults.songs" :key="idx" class="song-item">
						<!-- <image :src="song.cover || '/static/song/default-cover.jpg'" class="song-cover"
                            mode="aspectFill" /> -->
						<view class="song-info">
							<view class="song-title" v-html="highlightKeyword(song.song_name)"></view>
							<view class="song-artist" v-html="highlightKeyword(song.singer_name)"></view>
						</view>
						<view class="song-actions">
							<view class="action-btn" @click="orderSong(song)">
								<u-icon name="plus-circle" size="44" color="#3c82ff"></u-icon>
							</view>
							<!-- <view class="action-btn" @click="showSongMenu(song)">
                                <u-icon name="more-dot-fill" size="44" color="#999999"></u-icon>
                            </view> -->
						</view>
					</view>
				</view>
				<view v-else class="empty-result">
					<view class="empty-icon">🎵</view>
					<text class="empty-text">没有找到相关歌曲</text>
				</view>
			</view>

			<!-- 歌手结果 -->
			<view v-else-if="activeTabIndex === 1" class="singers-results">
				<view v-if="searchResults.singers.length > 0" class="singers-grid">
					<view v-for="(singer, idx) in searchResults.singers" :key="idx" class="singer-card" @click="goSingerDetail(singer)">
						<image :src="singer.singer_avatar || '/static/singer/default.jpg'" class="singer-avatar" mode="aspectFill" />
						<view class="singer-name" v-html="highlightKeyword(singer.singer_name)"></view>
					</view>
				</view>
				<view v-else class="empty-result">
					<view class="empty-icon">🎤</view>
					<text class="empty-text">没有找到相关歌手</text>
				</view>
			</view>
		</view>

		<!-- 歌曲操作弹窗 -->
		<u-popup v-model="showSongActionPopup" mode="bottom" border-radius="20" :mask-close-able="true">
			<view class="song-action-popup">
				<view class="popup-title">歌曲操作</view>
				<view class="action-list">
					<view class="action-item-popup" @click="orderSong(currentSong)">
						<u-icon name="plus-circle" size="32" color="#3c82ff" />
						<text class="action-text-popup">点歌</text>
					</view>
					<view class="action-item-popup" @click="grabSong(currentSong)">
						<u-icon name="play-circle" size="32" color="#4ecdc4" />
						<text class="action-text-popup">抢歌</text>
					</view>
					<view class="action-item-popup" @click="pinSong(currentSong)">
						<u-icon name="pushpin" size="32" color="#45b7d1" />
						<text class="action-text-popup">置顶</text>
					</view>
				</view>
				<u-button type="default" class="cancel-btn" @click="showSongActionPopup = false">取消</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
import request from '@/common/request.js';
import ktvCommand from '@/common/ktv-command-utils.js';

export default {
	data() {
		return {
			page: 1,
			orderId: '',
			searchKeyword: '',
			searchSuggestions: [],
			searchHistory: [],
			hotSearchTags: ['周杰伦', '邓紫棋', '林俊杰', '陈奕迅', '薛之谦', '毛不易', '李荣浩', '张学友'],
			hasSearched: false,
			isSearching: false,
			searchResults: {
				songs: [],
				singers: []
			},
			resultTabs: [
				{ name: '歌曲', count: 0 },
				{ name: '歌手', count: 0 }
			],
			activeTabIndex: 0,
			currentSong: {},
			showSongActionPopup: false,
			searchTimer: null
		};
	},
	computed: {
		totalResults() {
			console.log(this.searchResults.songs.length, this.searchResults.singers.length, 'totalResults');

			return this.searchResults.songs.length;
		}
	},
	onLoad(options) {
		this.orderId = options.order_id || '';
		this.loadSearchHistory();
	},
	methods: {
		goBack() {
			uni.navigateBack();
		},

		// 搜索输入
		onSearchInput(e) {
			this.searchKeyword = e.detail.value;

			// 清除之前的定时器
			if (this.searchTimer) {
				clearTimeout(this.searchTimer);
			}

			// 设置新的定时器，延迟搜索建议
			if (this.searchKeyword.trim()) {
				this.searchTimer = setTimeout(() => {
					this.getSearchSuggestions();
				}, 300);
			} else {
				this.searchSuggestions = [];
				this.hasSearched = false;
			}
		},

		// 搜索确认
		onSearchConfirm() {
			if (this.searchKeyword.trim()) {
				this.performSearch();
			}
		},

		// 获取搜索建议
		async getSearchSuggestions() {
			try {
				const res = await request.httpTokenRequest({
					url: `/api/ktv/search?content=${this.searchKeyword}&order_id=${this.orderId}&page=${this.page}`,
					method: 'get'
				});

				if (res.data.code === 1) {
					this.searchSuggestions = res.data.data || [];
				}
			} catch (error) {
				console.error('获取搜索建议失败:', error);
			}
		},

		// 执行搜索
		async performSearch() {
			if (!this.searchKeyword.trim()) return;

			this.isSearching = true;
			this.hasSearched = true;
			this.searchSuggestions = [];

			// 保存搜索历史
			this.saveSearchHistory(this.searchKeyword);

			try {
				const res = await request.httpTokenRequest({
					url: `/api/ktv/search?order_id=${this.orderId}&content=${this.searchKeyword}&page=${this.page}`,
					method: 'get'
				});

				if (res.data.code === 1) {
					const data = res.data.data || {};
					console.log(data, 'datal');

					this.searchResults = {
						songs: data.song.data || [],
						singers: data.singer || []
					};

					console.log(this.searchResults, 'searchResults');
				} else {
					throw new Error(res.data.msg || '搜索失败');
				}
			} catch (error) {
				console.error('搜索失败:', error);
				uni.showToast({
					title: error.message || '搜索失败',
					icon: 'none'
				});
			} finally {
				this.isSearching = false;
			}
		},

		// 选择搜索建议
		selectSuggestion(suggestion) {
			this.searchKeyword = suggestion;
			this.performSearch();
		},

		// 选择热门标签
		selectHotTag(tag) {
			this.searchKeyword = tag;
			this.performSearch();
		},

		// 选择搜索历史
		selectHistory(history) {
			this.searchKeyword = history;
			this.performSearch();
		},

		// 切换结果标签
		switchTab(index) {
			this.activeTabIndex = index;
		},

		// 高亮关键词
		highlightKeyword(text) {
			if (!this.searchKeyword || !text) return text;
			const keyword = this.searchKeyword.trim();
			const regex = new RegExp(`(${keyword})`, 'gi');
			return text.replace(regex, '<span style="color: #3c82ff; font-weight: bold;">$1</span>');
		},

		// 显示歌曲菜单
		showSongMenu(song) {
			this.currentSong = song;
			this.showSongActionPopup = true;
		},
		// 检查是否可以执行命令
		canExecuteCommand() {
			const now = Date.now();
			const timeSinceLastCommand = now - this.lastCommandTime;

			if (timeSinceLastCommand < this.commandCooldown) {
				const remainingTime = Math.ceil((this.commandCooldown - timeSinceLastCommand) / 1000);
				uni.showToast({
					title: `请等待${remainingTime}秒后再操作`,
					icon: 'none',
					duration: 1000
				});
				return false;
			}

			return true;
		},
		// 点歌
		async orderSong(song) {
			if (!this.canExecuteCommand()) return;
			this.updateLastCommandTime();
			const success = await ktvCommand.addSong(this.orderId, song.song_id);

			if (success) {
				uni.showToast({
					title: `已点：${song.song_name}`,
					icon: 'success'
				});

				// 点歌成功后刷新播放器状态
				setTimeout(() => {
					this.loadCurrentPlayingSong();
				}, 500);
			}
		},
		// 抢歌
		async grabSong(song) {
			if (!this.currentSong) return;
			if (!this.canExecuteCommand()) return;
			this.updateLastCommandTime();
			const success = await ktvCommand.insertSong(this.orderId, song.song_id);

			if (success) {
				uni.showToast({
					title: `已抢歌：${song.song_name}`,
					icon: 'success'
				});

				// 抢歌成功后刷新播放器状态
				setTimeout(() => {
					this.loadCurrentPlayingSong();
				}, 500);
			}
			this.showSongActionPopup = false;
		},

		// 置顶歌曲
		async pinSong(song) {
			if (!this.currentSong) return;
			if (!this.canExecuteCommand()) return;
			this.updateLastCommandTime();
			const success = await ktvCommand.insertSong(this.orderId, song.song_id);

			if (success) {
				uni.showToast({
					title: `已置顶：${song.song_name}`,
					icon: 'success'
				});

				// 置顶成功后刷新播放器状态
				setTimeout(() => {
					this.loadCurrentPlayingSong();
				}, 500);
			}
			this.showSongActionPopup = false;
		},
		// 更新最后命令时间
		updateLastCommandTime() {
			this.lastCommandTime = Date.now();
		},

		// 跳转歌手详情
		goSingerDetail(singer) {
			uni.navigateTo({
				url: `/pages/song/singer?name=${encodeURIComponent(singer.singer_name)}&order_id=${this.orderId}&singer_avatar=${singer.singer_avatar}`
			});
		},

		// 跳转歌单详情
		goPlaylistDetail(playlist) {
			uni.navigateTo({
				url: `/pages/song/playlist-detail?id=${playlist.id}&order_id=${this.orderId}`
			});
		},

		// 加载搜索历史
		loadSearchHistory() {
			try {
				const history = uni.getStorageSync('search_history') || [];
				this.searchHistory = history.slice(0, 10); // 最多保存10条
			} catch (error) {
				console.error('加载搜索历史失败:', error);
			}
		},

		// 保存搜索历史
		saveSearchHistory(keyword) {
			try {
				let history = uni.getStorageSync('search_history') || [];

				// 移除重复项
				history = history.filter((item) => item !== keyword);

				// 添加到开头
				history.unshift(keyword);

				// 限制数量
				history = history.slice(0, 10);

				uni.setStorageSync('search_history', history);
				this.searchHistory = history;
			} catch (error) {
				console.error('保存搜索历史失败:', error);
			}
		},

		// 删除单条历史
		removeHistory(index) {
			this.searchHistory.splice(index, 1);
			uni.setStorageSync('search_history', this.searchHistory);
		},

		// 清空搜索历史
		clearHistory() {
			uni.showModal({
				title: '确认清空',
				content: '确定要清空所有搜索历史吗？',
				success: (res) => {
					if (res.confirm) {
						this.searchHistory = [];
						uni.removeStorageSync('search_history');
					}
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.container {
	background: linear-gradient(180deg, #0d0d11 0%, #1a1a1f 100%);
	color: #ffffff;
	min-height: 100vh;
}

.search-header {
	padding: 40rpx 20rpx 20rpx 20rpx;
	// background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.search-bar {
	display: flex;
	align-items: center;
	background: rgba(255, 255, 255, 0.9);
	border-radius: 40rpx;
	padding: 15rpx 30rpx;
}

.search-input {
	flex: 1;
	margin-left: 15rpx;
	font-size: 28rpx;
	color: #333333;
}

.search-cancel {
	margin-left: 20rpx;
	color: #666666;
	font-size: 28rpx;
}

.suggestions-container,
.hot-search-container,
.history-container {
	padding: 30rpx 20rpx;
}

.suggestions-title,
.hot-search-title,
.history-title {
	font-size: 28rpx;
	font-weight: bold;
	color: #ffffff;
	margin-bottom: 20rpx;
}

.suggestions-list,
.history-list {
	display: flex;
	flex-direction: column;
	gap: 15rpx;
}

.suggestion-item,
.history-item {
	display: flex;
	align-items: center;
	gap: 15rpx;
	padding: 15rpx 20rpx;
	background: rgba(255, 255, 255, 0.05);
	border-radius: 12rpx;
	transition: all 0.3s;

	&:active {
		background: rgba(255, 255, 255, 0.1);
	}
}

.suggestion-text,
.history-text {
	flex: 1;
	font-size: 28rpx;
	color: #ffffff;
}

.hot-search-tags {
	display: flex;
	flex-wrap: wrap;
	gap: 15rpx;
}

.hot-tag {
	padding: 12rpx 20rpx;
	background: rgba(255, 255, 255, 0.1);
	border-radius: 20rpx;
	font-size: 26rpx;
	color: #ffffff;
	transition: all 0.3s;

	&:active {
		background: rgba(255, 255, 255, 0.2);
	}
}

.history-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.search-results {
	flex: 1;
	padding: 20rpx;
}

.result-stats {
	padding: 20rpx 0;
	font-size: 26rpx;
	color: #888888;
}

.result-tabs {
	display: flex;
	gap: 40rpx;
	margin-bottom: 30rpx;
	border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
}

.result-tab {
	padding-bottom: 15rpx;
	font-size: 30rpx;
	color: #888888;
	position: relative;
	transition: all 0.3s;

	&.active {
		color: #ffffff;
		font-weight: bold;

		&::after {
			content: '';
			position: absolute;
			bottom: 0;
			left: 0;
			right: 0;
			height: 4rpx;
			background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
			border-radius: 2rpx;
		}
	}
}

.tab-count {
	font-size: 24rpx;
	color: #666666;
}

.loading-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
	gap: 20rpx;
}

.loading-spinner {
	width: 40rpx;
	height: 40rpx;
	border: 4rpx solid #f3f3f3;
	border-top: 4rpx solid #3c82ff;
	border-radius: 50%;
	animation: spin 1s linear infinite;
}

@keyframes spin {
	0% {
		transform: rotate(0deg);
	}

	100% {
		transform: rotate(360deg);
	}
}

.loading-text {
	font-size: 28rpx;
	color: #888888;
}

.songs-list {
	display: flex;
	flex-direction: column;
	gap: 15rpx;
}

.song-item {
	display: flex;
	align-items: center;
	background: rgba(255, 255, 255, 0.05);
	border-radius: 15rpx;
	padding: 20rpx;
	backdrop-filter: blur(10rpx);
	transition: all 0.3s;

	&:active {
		background: rgba(255, 255, 255, 0.1);
	}
}

.song-cover {
	width: 80rpx;
	height: 80rpx;
	border-radius: 12rpx;
	margin-right: 20rpx;
}

.song-info {
	flex: 1;
	min-width: 0;
}

.song-title {
	font-size: 30rpx;
	font-weight: 500;
	color: #ffffff;
	margin-bottom: 8rpx;
}

.song-artist {
	font-size: 24rpx;
	color: #888888;
}

.song-actions {
	display: flex;
	align-items: center;
	gap: 15rpx;
}

.action-btn {
	padding: 10rpx;
	border-radius: 50%;
	transition: all 0.3s;

	&:active {
		transform: scale(0.9);
	}
}

.singers-grid {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 20rpx;
}

.singer-card {
	display: flex;
	flex-direction: column;
	align-items: center;
	background: rgba(255, 255, 255, 0.05);
	border-radius: 15rpx;
	padding: 20rpx;
	transition: all 0.3s;

	&:active {
		background: rgba(255, 255, 255, 0.1);
	}
}

.singer-avatar {
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
	margin-bottom: 15rpx;
}

.singer-name {
	font-size: 28rpx;
	font-weight: 500;
	color: #ffffff;
	text-align: center;
	margin-bottom: 8rpx;
}

.singer-desc {
	font-size: 24rpx;
	color: #888888;
}

.playlists-list {
	display: flex;
	flex-direction: column;
	gap: 15rpx;
}

.playlist-item {
	display: flex;
	align-items: center;
	background: rgba(255, 255, 255, 0.05);
	border-radius: 15rpx;
	padding: 20rpx;
	transition: all 0.3s;

	&:active {
		background: rgba(255, 255, 255, 0.1);
	}
}

.playlist-cover {
	width: 80rpx;
	height: 80rpx;
	border-radius: 12rpx;
	margin-right: 20rpx;
}

.playlist-info {
	flex: 1;
	min-width: 0;
}

.playlist-title {
	font-size: 30rpx;
	font-weight: 500;
	color: #ffffff;
	margin-bottom: 8rpx;
}

.playlist-desc {
	font-size: 24rpx;
	color: #888888;
}

.empty-result {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 50vh;
	gap: 20rpx;
}

.empty-icon {
	font-size: 80rpx;
}

.empty-text {
	font-size: 28rpx;
	color: #888888;
}

// 弹窗样式
.song-action-popup {
	padding: 30rpx;
	background: #23232b;
	border-radius: 20rpx 20rpx 0 0;
}

.popup-title {
	font-size: 28rpx;
	font-weight: bold;
	margin-bottom: 30rpx;
	color: #ffffff;
	text-align: center;
}

.action-list {
	display: flex;
	flex-direction: column;
	gap: 15rpx;
	margin-bottom: 30rpx;
}

.action-item-popup {
	display: flex;
	align-items: center;
	gap: 20rpx;
	padding: 20rpx;
	background-color: #1a1a1f;
	border-radius: 15rpx;
	transition: all 0.3s;

	&:active {
		transform: scale(0.98);
		background-color: #2a2a2f;
	}
}

.action-text-popup {
	font-size: 30rpx;
	color: #ffffff;
}

.cancel-btn {
	margin-top: 20rpx;
}

.header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 88rpx;
	margin-bottom: 20rpx;
	padding-top: 120rpx;
}

.header-title {
	font-size: 36rpx;
	font-weight: bold;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	-webkit-background-clip: text;
	-webkit-text-fill-color: transparent;
}

.header-right-button {
	background: rgba(255, 255, 255, 0.1);
	border-radius: 30rpx;
	padding: 10rpx 20rpx;
	display: flex;
	align-items: center;
	backdrop-filter: blur(10rpx);
}
</style>
